local prefabs =
{
    "reticuleaoe",
    "reticuleaoeping",
}

local function ReticuleTargetFn()
    return Vector3(ThePlayer.entity:LocalToWorldSpace(6.5, 0, 0))
end
------------------------------------------------------------------------------
---冲天刺落地伤害
local mydamage = TUNING.WATHGRITHR_SPEAR_DAMAGE
---需要添加动作的预制物
local mywuqi = "spear_wathgrithr"
---跳跃AOE落地范围
local aoefanwei = 7
---冷却时间
local lengque = TUNING.SPEAR_WATHGRITHR_LIGHTNING_LUNGE_COOLDOWN
---动作范围（装备上多大范围可以触发）
local actfanwei = 12
--起飞延迟
local PROJECTILE_DELAY = 4 * FRAMES
------------------------------------------------------------------------------
-- 基础矛冲天刺相关处理
local function BasicSpear_OnLeapPre(inst, doer, startpos, endpos)
    -- 检查是否在冷却中
    if inst.components.rechargeable and not inst.components.rechargeable:IsCharged() then
        return false
    end

    -- 处理冲天刺前的逻辑
    for _, v in pairs(TheSim:FindEntities(endpos.x, endpos.y, endpos.z, 4)) do
        if v.components and v.components.combat and v ~= doer then
            v.components.combat:GetAttacked(doer, mydamage)
            -- 如果该实体是可骑乘的（有 rideable 组件、有马鞍、没有骑手）
            if v.components and v.components.rideable and v.components.rideable.saddle and not v.components.rideable.rider then
                -- 让攻击者骑上这个生物
                doer.components.rider:Mount(v, true)
                return
            end
        end
    end

    -- 开始冷却
    if inst.components.rechargeable then
        inst.components.rechargeable:Discharge(lengque)
    end
end

local function BasicSpear_OnLeap(inst, doer, startingpos, targetpos)
    -- 生成跳跃特效
    SpawnPrefab("superjump_fx"):SetTarget(inst)

    -- 生成闪电效果
    local new = SpawnPrefab("lightning")
    new.Transform:SetPosition(targetpos:Get())
    -- 生成落地冲击波效果
    local fx = SpawnPrefab("groundpound_fx")
    local x, y, z = targetpos:Get()
    fx.Transform:SetPosition(x, y, z)
    fx.Transform:SetScale(0.7, 0.7, 0.7)
end

local function OnDischarged(inst)
    inst.components.aoetargeting:SetEnabled(false)
end

local function OnCharged(inst)
    inst.components.aoetargeting:SetEnabled(true)
end

-- 对基础矛(spear_wathgrithr)进行后初始化
AddPrefabPostInit(mywuqi, function(inst)
    -- 添加超级跳跃标签
    inst:AddTag("superjump")

    inst:AddComponent("aoetargeting")
    --inst.components.aoetargeting:SetAlwaysValid(true)
    inst.components.aoetargeting:SetAllowRiding(false)
    inst.components.aoetargeting.reticule.reticuleprefab = "reticuleaoe"
    inst.components.aoetargeting.reticule.pingprefab = "reticuleaoeping"
    inst.components.aoetargeting.reticule.targetfn = ReticuleTargetFn
    inst.components.aoetargeting.reticule.validcolour = { 1, .75, 0, 1 }
    inst.components.aoetargeting.reticule.invalidcolour = { .5, 0, 0, 1 }
    inst.components.aoetargeting.reticule.ease = true
    inst.components.aoetargeting.reticule.mouseenabled = true
    --inst.components.aoetargeting:SetRange(aoefanwei)
    inst.projectiledelay = PROJECTILE_DELAY
    inst.entity:SetPristine()

    if not TheWorld.ismastersim then return inst end

    -- 添加aoeweapon_leap组件
    inst:AddComponent("aoeweapon_leap")
    inst.components.aoeweapon_leap:SetAOERadius(aoefanwei)
    inst.components.aoeweapon_leap:SetOnLeaptFn(BasicSpear_OnLeap)
    inst.components.aoeweapon_leap:SetOnPreLeapFn(BasicSpear_OnLeapPre)

    -- 添加可充能组件
    inst:AddComponent("rechargeable")
    inst.components.rechargeable:SetChargeTime(lengque)
    inst.components.rechargeable:SetOnDischargedFn(OnDischarged)
    inst.components.rechargeable:SetOnChargedFn(OnCharged)

    inst:AddComponent("aoespell")
    inst.components.aoespell:SetSpellFn(function(inst, caster, pt)
        caster:PushEvent("combat_superjump", {
            targetpos = pt,
            weapon = inst,
        })
    end)

    -- 保存原始装备回调
    local oldonequipfn = inst.components.equippable.onequipfn
    local oldonunequipfn = inst.components.equippable.onunequipfn

    -- 重写装备回调
    inst.components.equippable:SetOnEquip(function(inst, owner)
        -- 安全调用原始函数
        if oldonequipfn then
            local success, err = pcall(oldonequipfn, inst, owner)
            if not success then
                print("Error in original onequipfn:", err)
            end
        end

        -- 检查 owner 是否存在且组件已加载
        if owner and owner:IsValid() and owner.components and owner.components.health then
            -- 示例：读取当前生命值
            local current_health = owner.components.health.currenthealth or 0
            -- 可在此处添加与 current_health 相关的逻辑
        else
            print("Owner or health component is invalid")
        end

        if owner then
            ACTIONS.SPEARLEAP.distance = actfanwei
            owner:AddTag("aoeweapon_leap_user")
        end
    end)

    -- 重写卸下回调
    inst.components.equippable:SetOnUnequip(function(inst, owner)
        -- 安全调用原始函数
        if oldonunequipfn then
            local success, err = pcall(oldonunequipfn, inst, owner)
            if not success then
                print("Error in original onunequipfn:", err)
            end
        end

        if owner then
            ACTIONS.SPEARLEAP.distance = nil
            owner:RemoveTag("aoeweapon_leap_user")
        end
    end)
end)
ACTIONS.CASTAOE.stroverridefn = function(act)
    return act.invobject ~= nil and act.invobject.components.aoeweapon_leap ~= nil and "冲天刺" or nil
end
local actions = {
    {
        id = 'SPEARLEAP',
        str = "冲天刺",
        strfn = nil,
        stroverridefn = function(act)
            return "冲天刺"
        end,
        fn = function(act)
            local weapon = act.invobject or act.doer.components.inventory:GetEquippedItem(EQUIPSLOTS.HANDS)
            if weapon and (weapon.prefab == "spear_wathgrithr") then
                -- 检查是否在冷却中
                if weapon.components.rechargeable and not weapon.components.rechargeable:IsCharged() then
                    return false
                end
                return true
            end
        end,
        state = nil,
        actiondata = {
            priority = 99,
        },
    },
}

local component_actions = {
    {
        type = 'POINT',
        component = 'aoeweapon_leap', --关联组件
        tests = {
            {
                action = 'SPEARLEAP',
                testfn = function(inst, doer, actions, right)
                    if right and inst:HasTag("superjump") then
                        -- 检查是否在冷却中
                        if inst.components.rechargeable and inst.components.rechargeable:IsCharged() then
                            doer:ListenForEvent("combat_superjump", function(doer, data)
                                return table.insert(actions, ACTIONS.SPEARLEAP)
                            end)
                        end
                    end
                end,
            },
        },
    },
}


--
for _, act in pairs(actions) do
    local addaction = AddAction(act.id, act.str, act.fn)
    if act.actiondata then
        for k, v in pairs(act.actiondata) do
            addaction[k] = v
        end
    end

    AddStategraphActionHandler('wilson', GLOBAL.ActionHandler(addaction, act.state))
    AddStategraphActionHandler('wilson_client', GLOBAL.ActionHandler(addaction, act.state))
end

for _, v in pairs(component_actions) do
    local testfn = function(...)
        local actions = GLOBAL.select(v.type == 'POINT' and -3 or -2, ...)
        for _, data in pairs(v.tests) do
            if data and data.testfn and data.testfn(...) then
                data.action = string.upper(data.action)
                table.insert(actions, GLOBAL.ACTIONS[data.action])
            end
        end
    end
    AddComponentAction(v.type, v.component, testfn)
end
